package com.blue.rpc.client;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

/**
 * 服务 => 远程主机列表
 * 
 * @author zhengj
 * @since 1.0 2016年10月17日
 */
public class ServiceHost
{
	private String service;
	private List<String> hostList = new ArrayList<>();
	private Random random = new Random();
	
	public ServiceHost(String service)
	{
		this.service = service;
	}
	
	public String getService()
	{
		return service;
	}
	
	public String getHost()
	{
		if (hostList.isEmpty())
			return null;
		
		if (hostList.size() == 1)
		{
			return hostList.get(0);
		}
		
		int index = random.nextInt(hostList.size());
		return hostList.get(index);
	}
	
	public void addHost(String host)
	{
		if (host == null || host.isEmpty())
			return;
		
		hostList.add(host);
	}
	
	public void removeHost(String host)
	{
		if (host == null || host.isEmpty())
			return;
		
		Iterator<String> iterator = hostList.iterator();
		while (iterator.hasNext())
		{
			String tmp = iterator.next();
			if (host.equals(tmp))
			{
				iterator.remove();
				break;
			}
		}
	}
	
	@Override
	public String toString()
	{
		return String.format("%s：%s", service, hostList);
	}
}
